package com.sky.config;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;

import java.util.ArrayList;
import java.util.List;

@Configuration
@Slf4j
public class JsonConfig {

    /*配置 fastjson 转换器*/
    @Bean
    public HttpMessageConverters fastjsonHttpMessageConverter() {
        // 1. 创建消息转换器
        FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();

        // 2. 创建配置对象 - 不要使用全局静态实例
        FastJsonConfig fastJsonConfig = new FastJsonConfig();

        // 3. 配置日期格式
        fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");

        // 4. 配置序列化特性
        fastJsonConfig.setSerializerFeatures(
                SerializerFeature.PrettyFormat,
//                SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteDateUseDateFormat,
                SerializerFeature.WriteNullNumberAsZero
        );

        // 7. 应用配置到转换器
        converter.setFastJsonConfig(fastJsonConfig);

        // 8. 配置支持的媒体类型
        List<MediaType> supportMediaTypeList = new ArrayList<>();
        supportMediaTypeList.add(MediaType.APPLICATION_JSON);
        supportMediaTypeList.add(MediaType.APPLICATION_OCTET_STREAM);
        // 添加其他必要类型...

        converter.setSupportedMediaTypes(supportMediaTypeList);

        // 9. 返回转换器
        return new HttpMessageConverters(converter);
    }

    // https://github.com/alibaba/fastjson/issues/1734 没有解
//    @PostConstruct
//    public void init(){
//        log.info("FastJson 注册全局编解码器");
//        SerializeConfig.getGlobalInstance().put(BaseEnum.class,new BaseEnumCodec());
//        ParserConfig.getGlobalInstance().putDeserializer(BaseEnum.class,new BaseEnumCodec());
//    }

//    @PostConstruct
//    public void init() {
//        System.out.println("FastJSON，全局配置序列化、反序列化器");
////        // 注册序列化器
////        JSONFactory.getDefaultObjectWriterProvider().register(BaseEnum.class, new EnumSerializer());
////
////        // 注册反序列化器
////        JSONFactory.getDefaultObjectReaderProvider().register(BaseEnum.class, new EnumDeserializer());
//    }

}
